package com.weigee.ktv.v.activity;

import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.TextUtils;

import com.l.d.app.library.eventbus.EventSend;
import com.l.d.app.library.eventbus.EventSendEntity;
import com.l.d.app.library.util.ToastUtil;
import com.weigee.ktv.m.EventTag;
import com.weigee.ktv.m.observer.DrawerLayoutObserver;
import com.weigee.ktv.v.fragment.MainFragment;

import org.simple.eventbus.Subscriber;

/**
 * Created by 林德 on 2017/4/12 15:24.
 * <p/>
 */
public final class SingleTaskActivity extends BaseActivity
{
    // 侧滑已全部关闭
    private boolean isDrawerAllClose;
    // 当前页面为主界面
    private boolean isMain;
    // 上次在主界面按下返回键的时间
    private long lastPressBackTimeMillis;

    @Override
    protected Fragment fragment(@Nullable final String fragmentTag)
    {
        isMain = false;
        Fragment fragment = ActivityUtil.fragment(fragmentTag);
        isMain = TextUtils.equals(fragment.getClass().getName(), MainFragment.class.getName());
        if (isMain)
        {
            EventSend.register(this);
        }
        return fragment;
    }

    @Override
    protected void onResume()
    {
        super.onResume();
        if (!isDrawerAllClose)
        {
            EventSend.with(EventTag.EVENT_MAIN_DRAWER_LAYOUT_CHANGE_STATE).msg(DrawerLayoutObserver.LEFT_CLOSE).build();
            EventSend.with(EventTag.EVENT_MAIN_DRAWER_LAYOUT_CHANGE_STATE).msg(DrawerLayoutObserver.RIGHT_CLOSE).build();
            lastPressBackTimeMillis = 0L;
        }
        isDrawerAllClose = true;
    }

    @Subscriber(tag = EventTag.EVENT_MAIN_DRAWER_ALL_CLOSE)
    private void notifyDrawerAllClose(EventSendEntity entity)
    {
        isDrawerAllClose = true;
    }

    @Subscriber(tag = EventTag.EVENT_MAIN_DRAWER_NOT_ALL_CLOSE)
    private void notifyDrawerNotAllClose(EventSendEntity entity)
    {
        isDrawerAllClose = false;
    }

    @Override
    public void onBackPressed()
    {
        if (!isDrawerAllClose)
        {
            EventSend.with(EventTag.EVENT_MAIN_DRAWER_LAYOUT_CHANGE_STATE).msg(DrawerLayoutObserver.LEFT_CLOSE).build();
            EventSend.with(EventTag.EVENT_MAIN_DRAWER_LAYOUT_CHANGE_STATE).msg(DrawerLayoutObserver.RIGHT_CLOSE).build();
            lastPressBackTimeMillis = 0L;
        }
        else if (isMain)
        {
            final long nowTimeMillis = System.currentTimeMillis();
            if (nowTimeMillis - lastPressBackTimeMillis <= 2500L)
            {
                finish();
                System.exit(0);
            }
            else
            {
                ToastUtil.makeTest(this, "再按一次返回键退出");
                lastPressBackTimeMillis = nowTimeMillis;
            }
        }
        else
        {
            super.onBackPressed();
        }
    }

    @Override
    protected void onDestroy()
    {
        if (isMain)
        {
            EventSend.unregister(this);
        }
        super.onDestroy();
    }
}
